// LGUIWaveEditor.cpp: implementation of the LGUIWaveEditor class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "LGUIWaveEditor.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LGUIWaveEditor::LGUIWaveEditor(int _x, int _y) : LGUIWindow(_x,_y,128,90)
{
  table=0;
}

LGUIWaveEditor::~LGUIWaveEditor()
{

}


void LGUIWaveEditor::draw(int xoff, int yoff)
{
  if (isDirty)
  {
    int dx=x+xoff;
    int dy=y+yoff;
    char *waveforms[4]=
    {
      "Saw",
      "Square",
      "Sine",
      "Triangle"
    };
    buffer.rectFillDarkFaded(dx,dy,dx+128,dy+h+1,COLOR(0x203060));
    buffer.hLine(dx,dy+h/2,dx+128,COLOR(0x18608f));

    if (table)
    {
      for (int i=0; i<128; i++)
      {
        buffer.putPixel(dx+i,dy+h/2-table->get(i)*(h/2-1),COLOR(0x60d0ff));
      }
      if (table->isStandard>=0)
      {
        buffer.drawTextShadow(waveforms[table->isStandard],dx+15,dy+h/2-5,COLOR(0x0080ff));
      }
    }
    else
    {
      buffer.drawTextShadow("No wave",dx+15,dy+h/2-5,COLOR(0x0080ff));
    }


    LRect dirty = *this;
    dirty.x += xoff;
    dirty.y += yoff;
    dirty.w++;
    dirty.h++;
    buffer.addDirtyRect(dirty);
    
    isDirty=false;
  }
}



void LGUIWaveEditor::penDown(int px, int py)
{
  if (!isInside(px,py)) return;
  px-=x;
  py-=y;
  py=h-py;
  py-=h/2;
  float f = float(py) / float(h/2);
  if (px>=0 && px<128)
  {
    if (table)
    {
      table->set(px,f);
      dragging=true;
      lastF=f;
      lastPos=px;
      redraw();
    }
  }
}

void LGUIWaveEditor::penUp(int px, int py)
{
  dragging=false;
}

inline int iabs(int i)
{
  return i<0 ? -i : i;
}

void LGUIWaveEditor::penMove(int px, int py, bool pressed)
{
  if (!dragging) return;
  if (py<y) py=y;
  if (py>=y+h) py=y+h;
  if (!isInside(px,y+5)) return;
  if (!table) return;
  px -= x;
  py -= y;
  py = h-py;
  py -= h/2;
  float f = float(py) / float(h/2);
  
  if (px>lastPos)
  {
    float slope = (f-lastF)/(px-lastPos);
    for (int i=lastPos; i<=px; i++)
    {
      table->set(i,lastF);
      lastF+=slope;
    }
  }
  else if (px<lastPos)
  {
    float slope = -(f-lastF)/(px-lastPos);
    for (int i=lastPos; i>=px; i--)
    {
      table->set(i,lastF);
      lastF+=slope;
    }
  }
  else if (px==lastPos)
  {
    table->set(px,f);
  }

  lastPos=px;
  lastF=f;
  redraw();
}